<?php
class Product_Service_Pickup
{
	public static $pickupStatus = array(
		"0" => "草稿",
		"1" => "已完成"
	);
	public static function getByCondition($condition=array(),$type='*',$page="",$pageSize=""){
		$model = new Product_Model_OrderPickup();
		$results = $model->getByCondition($condition,$type,$page,$pageSize);
		if(is_numeric($results)) return $results;
		foreach($results as $key => $value){
			$results[$key]["statusText"] = self::$pickupStatus[$value['op_status']];		
			$results[$key]["op_user_name"] = "系统";
			if($value['op_creater_id']>0){
				$user =  User_Service_User::getByUserId($value['op_creater_id']);
				$results[$key]["op_user_name"] = $user['name'];
			}

		}
		return $results;
	}
	
	public static function getPickupMap($condition=array(),$type='*',$page="",$pageSize=""){
		$model = new Product_Model_OrderPickupMap();
		$results = $model->getByCondition($condition,$type,$page,$pageSize);
		foreach($results as $key => $result){
			$results[$key]['product'] = Product_Service_Product::getByProductId($result['product_id']);
			$results[$key]['batch'] = Warehouse_Service_ProductsBatch::getById($result['wpb_id']);
		}
		return $results;
	}
	/**
	*确认下架
	@param pickupCode=>配货单单号
	@return ask 0失败 1成功 , msg 提示信息
	*/
	public static function confirmPickupTransaction($pickupCode){
		
		$session = new Zend_Session_Namespace('userAuth');
		$user_id=$session->userID;
		$customerBalance = new Customer_Model_CustomerBalance();
		$plan = new Plan_Service_Plan();
		$dbAdapter = $customerBalance->getAdapter();
		$dbAdapter->beginTransaction();
		$date=date("Y-m-d:H:i:s");
		try {
			$PickupMapmodel = new Product_Model_OrderPickupMap();
			$pickupmodel = new Product_Model_OrderPickup();
			$ordermodel = new Order_Model_Order();
			$planusagsModel=new Plan_Model_PlanUsage();
			$pickupRows=$pickupmodel->getByField('op_code',$pickupCode);
			if(empty($pickupRows)){
				return array (
					'ask' => 0,
					'msg' => "没有此下架单号!"
				);
			}elseif($pickupRows[0]['op_status']!=0){
				return array (
					'ask' => 0,
					'msg' => "操作失败,此下架单已确认!"
				);
			}
			
			if($pickupRows['op_product_cnt']==$pickupRows['op_order_cnt']){
				return array (
						'ask' => 0,
						'msg' => "一票一件类下架单，不能再此处操作!"
				);
			}
			$op_id=$pickupRows[0]['op_id'];
			$condition=array(
				'op_code'=>$pickupCode,
			);
			$pickupmapRows = $PickupMapmodel->getByCondition($condition,'*');
			$orders = array();//订单
			foreach($pickupmapRows as $key => $val){
				$orders[$val['orders_code']] = $val['orders_code'];//去除重复订单
				$orderRow = Order_Service_Order::getByOrdersCode($val['orders_code']);
				
				$ProBrow=Warehouse_Service_ProductsBatch::getById($val['wpb_id']);
				
				$current_quantity=$ProBrow['wpb_quantity']+$ProBrow['wpb_quantity_hold']-$val['opm_quantity'];
				$current_quantity_hold=$ProBrow['wpb_quantity_hold']-$val['opm_quantity'];
				$updateRow=array(
					'wpb_quantity_hold'=>$current_quantity_hold,
					'wpb_status'=>	$current_quantity<0||$current_quantity_hold<0||($current_quantity==0&&$current_quantity_hold==0)?0:1,
				);
				if($updateRow['wpb_quantity_hold']<0||$ProBrow['wpb_quantity']<0){
					throw new Exception("数据异常，批次 ".$ProBrow['wpb_id']." 可用数量或冻结数量小于0");
				}
				if(Warehouse_Service_ProductsBatch::update($updateRow,$val['wpb_id'])){
					$option =  array('type'=>2,"putaway_code"=>$ProBrow['putaway_code'],"putaway_lot_number"=>$ProBrow['putaway_lot_number'],"quantity"=>$val['opm_quantity']);
					$palletNum = $plan->getBatchPallet($option);
					$order = Order_Service_Order::getByOrdersCode($val['orders_code']);
					//更新pallet
					if($palletNum>0){
						$planusagsModel->updatePlanUsage($order['customer_id'],'pallet',$palletNum*-1);
					}
					if($order['orders_status']!=3 || $order['process_status']!=2){
						$dbAdapter->rollback();
						return array (
								'ask' =>0,
								'msg' => '订单状态不正确!'
						);
					}
					
					$warehouse_productBatch = Warehouse_Service_ProductsBatch :: getByfield('wpb_id', $val['wpb_id']);			
					$condition = array(
						"product_id"=>$warehouse_productBatch['product_id'],
						"ws_code"=>$warehouse_productBatch['ws_code'],
					);
					$warehouse_product = Warehouse_Service_Products :: getByCondition($condition);
					$wp_quantity_hold = $warehouse_product['wp_quantity_hold'] - $val['opm_quantity'];
					//更新货架产品 数量
					$warehouse_product_row = array (
						'wp_quantity_hold' => $warehouse_product['wp_quantity_hold'] - $val['opm_quantity'],
// 						'wp_status' => $warehouse_product['wp_quantity']==0&&$warehouse_product['wp_quantity_hold']==$val['opm_quantity']?0:1,
					);
					//异常判断
					if($warehouse_product_row['wp_quantity_hold']<0){
						throw new Exception("数据异常，货架库存 ".$warehouse_product['wp_id']." 冻结数量小于配货数");
					}
					Warehouse_Service_Products::update($warehouse_product_row,$warehouse_product['wp_id']);
					
					//货架使用日志
					$WarehouseProductsLog = array(
							'wpl_refId' => $val['orders_code'],
							'user_id' => $user_id,
							'warehouse_id' => $warehouse_product['warehouse_id'],
							'ws_code' => $warehouse_product['ws_code'],
							'wpl_proc_type' => 0, //扣减库存
							'wpl_note' => '下架确认更改货架库存，冻结库存由'.$warehouse_product['wp_quantity_hold'].'变为'.$wp_quantity_hold."可用库存".$warehouse_product['wp_quantity'],
					);
					if (!Warehouse_Service_Products::CreateWarehouseProductsLog($WarehouseProductsLog)) {
						throw new Exception("订单：".$val['orders_code']." 货架 ".$warehouse_product['ws_code']." 写入使用日志失败失败");
					
					}
					
					//写入使用日志
					$addWSPU=array(
						'wpu_type'=>1,
						'wpu_proc_type'=>0,
						'wpu_refId'=>$val['orders_code'],
						'wpu_quantity'=>$val['opm_quantity'],
						'wpu_current_qty'=>$current_quantity,
						'wpu_note'=>'下架确认,可用库存：'.$ProBrow['wpb_quantity'].'冻结库存from:'.$ProBrow['wpb_quantity_hold']."to $current_quantity_hold",
						'wpb_id'=>$val['wpb_id'],
						'wpu_create_time'=>$date,
					);
					if(!Warehouse_Service_ProductUseage::create($addWSPU)){
						$dbAdapter->rollback();
						return array (
							'ask' =>0,
							'msg' => '写下架日志失败!'
						);
					}
				}else{
					$dbAdapter->rollback();
					return array (
						'ask' =>0,
						'msg' => '扣批次失败!'
					);
				}
			}
			foreach($orders as $v){//更新订单状态
				if(!$ordermodel->updateByOrdersCode(array('process_status'=>3),$v)){
					$dbAdapter->rollback();
					return array (
							'ask' =>0,
							'msg' => '更新订单：'.$v.'状态失败!'
					);
				}
			}
			
			
			
			if(!$pickupmodel->update(array('op_status'=>1,'op_last_update'=>$date),$op_id)){
				$dbAdapter->rollback();
				return array (
					'ask' =>0,
					'msg' => '更新配货单状态失败!'
				);
			}
			$dbAdapter->commit();
			return array (
				'ask' => 1,
				'msg' => "操作成功"
			);
		} catch (Exception $e) {
			$dbAdapter->rollback();
			return array (
				'ask' =>0,
				'msg' => '程序内部错误'.$e->getMessage()
			);
		}
	}
}